package com.example.listviewtest;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;
import java.util.zip.Inflater;

public class FruitAdapter extends ArrayAdapter<Fruit> {
    private int resourceId;
    public FruitAdapter(@NonNull Context context, int resource, @NonNull List<Fruit> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }
    //重写方法:每个子项被滚动到屏幕内会调用这个方法
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // 适配器获取子项对象的方法
        Fruit fruit = getItem(position);
        LayoutInflater lf = LayoutInflater.from(getContext());
        View view;
        ViewHolder vh;
        if(convertView != null){
            view = convertView;
            //直接获取两控件
            vh = (ViewHolder)view.getTag();
        }else {
            // 加载到parent布局中 false表示不为这个View添加父布局
            // view即子项
            view = lf.inflate(resourceId,parent,false);
            vh = new ViewHolder();
            //找到两控件
            vh.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            vh.fruitName = (TextView) view.findViewById(R.id.fruit_name);
            view.setTag(vh);
        }
        // 获取自定义布局的控件
        // 设置数据
        vh.fruitImage.setImageResource(fruit.getImageId());
        vh.fruitName.setText(fruit.getName());
        return view;
    }
    //内部类：用于对控件的实例进行缓存，没有必要每次都通过findViewById() 方法来获取控件实例
    class ViewHolder{
        ImageView fruitImage;
        TextView fruitName;
    }
}
